<?php

include("dal_mysql.php");
include("yahooboss.class.php");

class BAL
{
    public $db;
    public $params;
    public $query;
    public $yahoo;

    function  __construct()
    {
        $this->db = new Database();
        $this->yahoo = new YahooBoss();
    }

    public function getProvidersList()
    {
        $this->query = "SELECT id, site_label, site_url, image_url, last_modified
                        FROM sites";

        return $this->db->getResults($this->query);
    }

    public function getSearchResults($provider="linkedin.com", $keyword="Uzair Seedat")
    {
        $format = 'xml';
        $query = "site:" . $provider . " " . $keyword;
        $results_array = array();

        $query = urlencode($query);
         
        $results = $this->yahoo->YahooWebSearch($query, $format);

        foreach ($results->resultset_web->result as $result)
        {
            $results_array[] = $result;
        }
        
        return $results_array;
    }

    public function setSearchKeyword($queryString)
    {
        $this->params = $this->getQueryStringValues($queryString);

        if($this->params)
        {
            if(isset ($this->params["searchValue"]))
            {
                if(is_array($this->params["searchValue"]) && count($this->params["searchValue"]) > 0)
                {
                    $_SESSION["searchKeyword"] = $this->params["searchValue"][0];
                }
                else
                {
                    $_SESSION["searchKeyword"] = $this->params["searchValue"];
                }
            }
        }
    }

    public function getProvider($query_string)
    {
        $provider = "yahoo.com";

        $this->params = $this->getQueryStringValues($query_string);

        if($this->params)
        {
            if(isset ($this->params["keyColumn"]) && isset ($this->params["keyValue"]))
            {
                $provider = $this->params["keyValue"][0];
            }
        }

        return $provider;
    }

    public function getLinkedInResults($queryString)
    {
        $this->query = "SELECT";

        $this->params = $this->getQueryStringValues($queryString);
            //params now contains QuesryString values as array
            if($this->params)
            {
                //check what columns to display
                if(isset ($this->params["column"]))
                {
                    $this->query = $this->appendColumns($this->query, $this->params["column"], "parts");
                }
                else
                {
                    $this->query .= " id, part_no, description, list_price, last_modified";
                    $this->query .= " FROM parts";
                }


                //check what columns to filter based on value
                if(isset ($this->params["keyColumn"]) && isset ($this->params["keyValue"]))
                {
                    $this->query = $this->appendConditions($this->query, $this->params["keyColumn"], $this->params["keyValue"]);
                }

                if(isset ($this->params["searchColumn"]) && isset ($this->params["searchValue"]))
                {
                    $this->query = $this->appendSearching($this->query, $this->params["searchColumn"], $this->params["searchValue"]);
                }

                //check if sorting is required
                if(isset ($this->params["sortByColumn"]))
                {
                    if(isset ($this->params["sortByOrder"]))
                    {
                        $this->query = $this->appendSorting($this->query, $this->params["sortByColumn"], $this->params["sortByOrder"]);
                    }
                    else
                    {
                        $this->query = $this->appendSorting($this->query, $this->params["sortByColumn"]);
                    }
                }

                //check for pagination
                if(isset ($this->params['startRow']) && isset ($this->params['numberOfRows']))
                {
                    $this->query = $this->appendLimit($this->query, $this->params['startRow'][0], $this->params['numberOfRows'][0]);
                }
            }

//            if(!isset ($this->params["keyColumn"]) && !isset ($this->params["keyValue"]) &&
//                     !isset ($this->params["searchColumn"]) && !isset ($this->params["searchValue"]))
//            {
//                $from_pos = strpos($this->query, "FROM parts");
//
//                if($from_pos != FALSE)
//                {
//                    $upto_from = substr($this->query, 0, $from_pos + 10);
//                    $after_from = substr($this->query, $from_pos + 10);       //because the words FROM parts are 10 charaters
//
//                    $this->query = $upto_from . " WHERE parent_id = '1' " . $after_from;
//                }
//
//            }

            return $this->db->getResults($this->query);
    }

    public function getCountAtCurrentLevel()
    {
        return count($this->db->getResultsWithoutLimit($this->query));
    }

    public function getQueryStringValues($query_string)
    {
        $query  = explode('&', $query_string);
        $params = array();

        foreach( $query as $param )
        {
            list($name, $value) = explode('=', $param);
            $params[urldecode($name)][] = urldecode($value);
        }

        return $params;
    }

    public function appendColumns($query, $column_names, $table)
    {
        $query .= " ";

        if(is_array($column_names))
        {
            foreach($column_names as $column)
            {
                $query .= $column;
                $query .= ",";
            }

            $query = rtrim($query, ',');
        }
        else
        {
            $query .= $column_names;
        }

        $query .= " FROM ";
        $query .= $table;

        return $query;
    }

    public function appendConditions($query, $column_names, $value_list)
    {
        if(count($column_names) == count($value_list))
        {
            $query .= " WHERE ";

            if(is_array($column_names))
            {
                for($i = 0; $i < count($column_names); $i++)
                {
                    $query .= $column_names[$i];
                    $query .= "=";
                    $query .= "'" . $value_list[$i] . "'";

                    if($i < count($column_names) - 1)
                    {
                        $query .= " AND ";
                    }
                }
            }
            else
            {
                $query .= $column_names;
                $query .= "=";
                $query .= "'" . $value_list . "'";
            }
        }

        return $query;
    }

    public function appendSearching($query, $column_names, $keywords)
    {
        if(is_array($column_names) && is_array($keywords) && count($column_names) == count($keywords))
        {
            $where_pos = strpos($query, "WHERE");

            if($where_pos != FALSE)     //query already contains a WHERE clause
            {
                $before_where = substr($query, 0, $where_pos);
                $after_where = substr($query, $where_pos + 5);      //because the word WHERE is 5 charaters

                $like_clause = " WHERE ";

                for($i = 0; $i < count($column_names); $i++)
                {
                    $keywords[$i] = str_replace("*", "%", $keywords[$i]);
                    $keywords[$i] = str_replace("?", "_", $keywords[$i]);

                    $like_clause .= $column_names[$i];
                    $like_clause .= " LIKE ";
                    $like_clause .= "'" . $keywords[$i] . "'";

                    if($i < count($column_names) - 1)
                    {
                        $query .= " OR ";
                    }
                }

                $query = $before_where . $like_clause . $after_where;
            }
            else
            {
                $query .= " WHERE ";

                for($i = 0; $i < count($column_names); $i++)
                {
                    $keywords[$i] = str_replace("*", "%", $keywords[$i]);
                    $keywords[$i] = str_replace("?", "_", $keywords[$i]);

                    $query .= $column_names[$i];
                    $query .= " LIKE ";
                    $query .= "'" . $keywords[$i] . "'";

                    if($i < count($column_names) - 1)
                    {
                        $query .= " OR ";
                    }
                }

                $query = rtrim($query, ',');
            }
        }

        return $query;
    }

    public function appendSorting($query, $column_names, $order="ASC")
    {
        if(count($column_names) > 0)
        {
            $query .= " ORDER BY ";

            if(is_array($column_names))
            {
                if(is_array($order) && count($column_names) == count($order))
                {
                    for($i = 0; $i < count($column_names); $i++)
                    {
                        $query .= $column_names[$i];
                        $query .= " ";
                        $query .= $order[i];
                        $query .= ",";
                    }

                    $query = rtrim($query, ',');
                }
                else
                {
                    foreach($column_names as $column)
                    {
                        $query .= $column;
                        $query .= ",";
                    }

                    $query = rtrim($query, ',');

                    //$order may still be an array but not with same count as columns
                    if(!is_array($order))
                    {
                        $query .= " ";
                        $query .= $order;
                    }
                }
            }
            else
            {
                $query .= $column_names;

                if(!is_array($order))
                {
                    $query .= " ";
                    $query .= $order;
                }
            }
        }

        return $query;
    }

    public function appendLimit($query, $startRecord, $recordCount)
    {
        if($recordCount > 0)
        {
            $query .= " LIMIT ";
            $query .= $startRecord - 1;     //since mySQL uses 0-based rec index
            $query .= ", ";
            $query .= $recordCount;
        }

        return $query;
    }
}
?>
